package com.web.webstart.base.util.jpa;

import com.web.webstart.base.util.DateUtils;
import com.web.webstart.base.util.Identities;
import com.web.webstart.base.util.XaUtil;
import org.apache.commons.lang3.StringUtils;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;


public class SearchFilter {

	//LIKEIGNORE 模糊查找不区分大小写
	//LIKE 模糊查找区分大小写
	public enum Operator {
		EQ, IN , LIKE, LIKEIGNORE, LIKEPINYIN, GT, LT, GTE, LTE, NE, BETWEEN,ISNULL
		//EQ等于, IN包含, LIKE, LIKEIGNORE(是一个闭区间), LIKEPINYIN 忽略大小写、中文和拼音, GT大于, LT小于, GTE大于等于, LTE小于等于, NE不等于,非like;ISNULL空,
		//BETWEEN都用英文逗号分割; search_BETWEEN or Operator.BETWEEN
		//IN 是一个集合,List or Set  搜 Operator.IN(传递集合对象) 或者 搜索 search_IN(传递json串)  全局;如:
	}

	public String fieldName;
	public Object value;
	public Operator operator;

	/**
	 * @param fieldName 这个是实体的名称,不是表的名称
	 */
	public SearchFilter(String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	//key都是uuid2处理过的
	public static Map<String, SearchFilter> parse(Map<String, Object> filterParams) {
		Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();

		for (Entry<String, Object> entry : filterParams.entrySet()) {
			String[] names = StringUtils.split(entry.getKey(), "_", 2);//可能有的entity字段也包含_,因此这里限制分割次数
			Object value = entry.getValue();
			if (names.length < 2) {
				throw new IllegalArgumentException(entry.getKey() + " is not a valid search filter name");
			}
			if(names.length == 3){
				if("SHORTDATE".equals(names[2])){
					String fieldValue = (String)value;
					if(XaUtil.isNotEmpty(fieldValue)){
						value = fieldValue.replace("DistanceUtils", "").replace(":", "").replace("-", "").subSequence(0, 8);
					}
				}
				if("DATE".equals(names[2])){
					String fieldValue = (String)value;
					if(XaUtil.isNotEmpty(fieldValue)){
					//	fieldValue = fieldValue.replace("DistanceUtils", "").replace(":", "").replace("-", "");
						if("LTE".equals(names[0])){ 
						 	try {
						 	 Date d= org.apache.commons.lang3.time.DateUtils.parseDate(value.toString(), new String[]{"yyyy-MM-dd"});
						 	 value= DateUtils.YYYYMMDD.format(org.apache.commons.lang3.time.DateUtils.addDays(d, 1));
						 	} catch (ParseException e) {
								e.printStackTrace();
							} 
						}else{
							value = fieldValue+ "000000";
						}
					}
				}
			}
			SearchFilter filter = new SearchFilter(names[1], Operator.valueOf(names[0]), value);
			if(XaUtil.isNotEmpty(entry.getValue())){
				filters.put(filter.fieldName + Identities.uuid2(), filter);
			}
		}
		return filters;
	}
}
